﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using LostOrFind.Attributes;
using LostOrFind.Context;
using LostOrFind.Models.APIs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;

namespace LostOrFind.APIs;

[ApiController]
[Route("api/[controller]")]
public class UserController : Controller
{
    // GET
    private MyDbContext _context;
    private readonly IConfiguration _configuration;
    public UserController(MyDbContext context,IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration;
    }

    /**
     * 前端使用该接口进行登录并获得一个新的token，旧的token会失效。
     * 进行其他操作是需要在header中传入token才能使用
     */
    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginUser user)
    {
        var username = user.Username;
        var password = user.Password;
        // Console.WriteLine(user);
        // 在这里根据用户名和密码验证用户身份
        var res = await IsValidUser(username, password);
        if (res.Item1)
        {
            var token = GenerateToken(username);
            return Ok(new { Token = token,Id = res.Item2 });
        }

        return Unauthorized();
    }
    
    private async Task<(bool,int)> IsValidUser(string username, string password)
    {
        var user = await _context.Users.Where(u => u.Name == username).FirstOrDefaultAsync();
        if (user == null) return (false,-1);
        return (user.Password == password,user.Id);
    }

    private string GenerateToken(string username)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]!));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _configuration["Jwt:Issuer"],
            audience: _configuration["Jwt:Audience"],
            claims: new[] { new Claim(ClaimTypes.Name, username) },
            expires: DateTime.Now.AddHours(1),
            signingCredentials: credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
    
    [HttpGet("id")]
    [OnlyDevelopment]
    public async Task<IActionResult> GetUser(int id)
    {
        var user = await _context.Users.FindAsync(id);
        return Ok(user);
    }
    

    [HttpGet("test")]
    [OnlyDevelopment]
    [Authorize]
    public IActionResult Test()
    {
        // 在这里进行其他操作，需要验证token是否有效
        return Ok("Token is valid");
    }

    [HttpGet("userinfo")]
    [Authorize]
    [OnlyDevelopment]
    public IActionResult GetUserInfo()
    {
        var username = User.Identity.Name;
        // 在这里根据用户名获取用户信息
        return Ok(username);
    }
    
}